package com.zuofei.xmpp.fragment;

import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zuofei.xmpp.R;
import com.zuofei.xmpp.XmppApplication;
import com.zuofei.xmpp.activity.ChatActivity;
import com.zuofei.xmpp.dbhelper.ContactOpenHelper;
import com.zuofei.xmpp.provider.ContactsProvider;
import com.zuofei.xmpp.utils.ThreadUtils;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ContactsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ContactsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ContactsFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ListView listView;
    private CursorAdapter mAdapter;


    public ContactsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ContactsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ContactsFragment newInstance(String param1, String param2) {
        ContactsFragment fragment = new ContactsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        init();
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_contacts, container, false);
        initView(view);
        return view;
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        initData();
        initListener();
        super.onActivityCreated(savedInstanceState);
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void init() {
        registerContentObserver();
    }
    private void initView(View view) {
         listView = view.findViewById(R.id.listview);
        
    }

    private void initListener() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = mAdapter.getCursor();
                cursor.moveToPosition(position);
                //拿到账号->发送消息的时候需要
                String account = cursor.getString(cursor.getColumnIndex(ContactOpenHelper.ContactTable.ACCOUNT));
                //拿到nickname->显示效果
                String nickname = cursor.getString(cursor.getColumnIndex(ContactOpenHelper.ContactTable.NICKNAME));
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra(ChatActivity.CLICKACCOUNT,account);
                intent.putExtra(ChatActivity.CLICKNICKNAME,nickname);
                startActivity(intent);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initData() {


        //开启线程,同步花名册
        getFriendList();
    }

    /**
     * 获取好友列表
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void getFriendList() {
        setOrUpdateAdapter();

    }

    /**
     * 设置或更新adapter
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setOrUpdateAdapter() {
        //判断adapter是否存在
        if(mAdapter != null){
            //刷新adapter就行了
            mAdapter.getCursor().requery();
            return;
        }

        ThreadUtils.runInThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                //得到花名册
                final Cursor c = XmppApplication.getInstance().getContentResolver().query(ContactsProvider.URI_CONTACT,null,null,null);
                //假如没有数据
                if(c.getCount() <= 0){
                    return;
                }
                //设置adapter,然后显示数据
                ThreadUtils.runInUIThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter = new CursorAdapter(getActivity(),c) {
                            @Override
                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                                View view = View.inflate(context,R.layout.item_contact,null);
                                return view;
                            }

                            @Override
                            public void bindView(View view, Context context, Cursor cursor) {
                                ImageView ivHead = view.findViewById(R.id.head);
                                TextView tvAccount = view.findViewById(R.id.account);
                                TextView tvNickName = view.findViewById(R.id.nickname);
                                String account = cursor.getString(c.getColumnIndex(ContactOpenHelper.ContactTable.ACCOUNT));
                                String nickname = cursor.getString(c.getColumnIndex(ContactOpenHelper.ContactTable.NICKNAME));
                                tvAccount.setText(account);
                                tvNickName.setText(nickname);
                            }
                        };
                        listView.setAdapter(mAdapter);
                    }
                });
            }
        });
    }





    MyContentObserver mMyContentObserver = new MyContentObserver(new Handler());
    /**
     * 注册监听
     */
    public void registerContentObserver(){
        getActivity().getContentResolver().registerContentObserver(ContactsProvider.URI_CONTACT,true,mMyContentObserver);
    }
    /**
     * 反注册监听
     */
    public void unRegisterContentObserver(){
        getActivity().getContentResolver().unregisterContentObserver(mMyContentObserver);
    }
    /**
     * 监听数据库记录的改变
     */
    class MyContentObserver extends ContentObserver{

        /**
         * Creates a content observer.
         *
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public MyContentObserver(Handler handler) {
            super(handler);
        }

        /**
         * 如果数据库数据改变会在这个方法收到通知
         */
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            //更新adapter或刷新adapter
            setOrUpdateAdapter();
        }
    }

    @Override
    public void onDestroy() {
        //按照常理，我们Fragment销毁，那么我们就不应该去继续监听，但是，实际，我们需要
        //一直监听对应roster的改变
        //所以，我们把联系人的监听和同步操作放到Service中去
        unRegisterContentObserver();

        super.onDestroy();
    }
}
